
//  USStickerPickerView.m
//  us
//
//  Created by lhx on 2025/4/15.
//

#import "USStickerPickerView.h"
#import "USStickerToolViewCell.h"
#import "USStickerViewCell.h"
#import "UIStickerFooterView.h"
#import "TouchableMaskView.h"

@interface USStickerPickerView () <UICollectionViewDelegate, UICollectionViewDataSource, UIPageViewControllerDataSource, UIPageViewControllerDelegate>

@property (nonatomic, strong) UICollectionView *toolBar;
@property (nonatomic, strong) UIPageViewController *pageViewController;
@property (nonatomic, strong) NSArray<USStickerModel *> *stickerGroups;
@property (nonatomic, assign) NSInteger currentGroupIndex;
@property (nonatomic, strong) NSMutableArray<UICollectionViewController *> *pageControllers;

@property (nonatomic, assign) BOOL showCloseButton; // 是否显示删除按钮
@property (nonatomic, assign) BOOL showEmptyButton; // 是否显示清除按钮

@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) UIButton *emptyButton;

@property (nonatomic, strong) UIView *stickerMaskView;

@end

@implementation USStickerPickerView

- (instancetype)initWithStickerShowCloseButton:(BOOL)showDelete{
    return [[USStickerPickerView alloc] initWithStickerShowCloseButton:showDelete andShowEmpty:NO];
}

- (instancetype)initWithStickerShowCloseButton:(BOOL)showDelete andShowEmpty:(BOOL)showEmpty {
    if (self = [super initWithFrame:CGRectZero]) {
        self.showCloseButton = showDelete;
        self.showEmptyButton = showEmpty;
        self.currentGroupIndex = 0;
        self.pageControllers = [NSMutableArray array];

        [self initDefaultStickerGroups];
        [self setupToolBar];
        [self setupPageView];
        
    }
    return self;
}


/// 使用默认贴纸
- (void)initDefaultStickerGroups {
    NSMutableArray *groups = [NSMutableArray array];

    // 添加普通贴纸组
    [groups addObject:[self stickerGroupWithPrefix:@"sticker_0_" count:12 size:CGSizeZero isOriginal:YES]];
    [groups addObject:[self stickerGroupWithPrefix:@"sticker_1_" count:12 size:CGSizeZero isOriginal:YES]];
    [groups addObject:[self stickerGroupWithPrefix:@"sticker_2_" count:8 size:CGSizeZero isOriginal:YES]];
    [groups addObject:[self stickerGroupWithPrefix:@"sticker_3_" count:11 size:CGSizeZero isOriginal:YES]];
    [groups addObject:[self stickerGroupWithPrefix:@"sticker_4_" count:12 size:CGSizeZero isOriginal:YES]];

    // 添加 emoji 贴纸组（28x28 尺寸，编号从 01 开始）
//    [groups addObject:[self stickerGroupWithPrefix:@"ic_emj_" count:29 size:CGSizeMake(60, 60) isOriginal:YES startIndex:0 zeroPadding:YES]];

    self.stickerGroups = groups;

    // 默认选中当前分组
    if (self.stickerGroups.firstObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentGroupIndex inSection:0];
            [self.toolBar selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        });
    }
}

/// 创建一个贴纸分组（默认从 0 开始，不补 0）
- (USStickerModel *)stickerGroupWithPrefix:(NSString *)prefix count:(NSInteger)count size:(CGSize)size isOriginal:(BOOL)isOriginal {
    return [self stickerGroupWithPrefix:prefix count:count size:size isOriginal:isOriginal startIndex:0 zeroPadding:NO];
}

/// 通用创建贴纸组的方法
- (USStickerModel *)stickerGroupWithPrefix:(NSString *)prefix
                                     count:(NSInteger)count
                                      size:(CGSize)size
                                isOriginal:(BOOL)isOriginal
                                startIndex:(NSInteger)start
                               zeroPadding:(BOOL)zeroPadding {
    USStickerModel *groupModel = [USStickerModel new];
    groupModel.isOriginal = isOriginal;
    NSMutableArray <USStickerModel *>*stickers = [NSMutableArray array];

    for (NSInteger i = 0; i < count; i++) {
        USStickerModel *sticker = [USStickerModel new];
        sticker.size = size;
        sticker.isOriginal = isOriginal;
        NSInteger index = start + i;
        NSString *name = zeroPadding ? [NSString stringWithFormat:@"%@%02ld", prefix, (long)index]
                                     : [NSString stringWithFormat:@"%@%ld", prefix, (long)index];
        sticker.name = name;
        [stickers addObject:sticker];
    }
    groupModel.name = stickers.firstObject.name;
    groupModel.size = size;
    groupModel.stickers = stickers;
    return groupModel;
}



- (void)reloadWithStickerGroups:(NSArray<USStickerModel *> *)groups {
    self.stickerGroups = groups;
    self.currentGroupIndex = 0;

    // 清除旧的 pageControllers
    [self.pageControllers removeAllObjects];

    // 重新创建新的 pageControllers
    for (NSInteger i = 0; i < groups.count; i++) {
        
        USStickerModel *group = groups[i];
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        if (group.size.width > 0) {
            
            layout.itemSize = group.size;
            
        }else{
            CGFloat width = (ScreenWidth - 16 * 2 - 10 * 3)/4.0;
            if (width > 120) {
                width = 120;
            }
            layout.itemSize = CGSizeMake(width , width);
        }
        layout.minimumInteritemSpacing = 10;
        layout.minimumLineSpacing = 10;
        layout.sectionInset = UIEdgeInsetsMake(12, 16, 0, 16);
        UICollectionViewController *vc = [[UICollectionViewController alloc] initWithCollectionViewLayout:layout];
        vc.view.backgroundColor = UIColor.clearColor;
        vc.collectionView.backgroundColor = UIColor.clearColor;
        vc.collectionView.delegate = self;
        vc.collectionView.dataSource = self;
        vc.collectionView.tag = i;
        [vc.collectionView registerClass:[USStickerViewCell class] forCellWithReuseIdentifier:@"USStickerViewCell"];
        [self.pageControllers addObject:vc];
    }

    [self.toolBar reloadData];
    if (groups.firstObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.toolBar selectItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentGroupIndex inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        });
    }
    if (self.pageControllers.count > 0) {
        [self.pageViewController setViewControllers:@[self.pageControllers[0]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    }
}


- (void)showStickerPickerWithAllowTapDismiss:(BOOL)allowDismiss{
    
    if (self.hidden != YES) {
        return;
    }
    
    self.hidden = NO;
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(0);
    }];
    [UIView animateWithDuration:0.3 animations:^{
        [self.superview layoutIfNeeded];
    }completion:^(BOOL finished) {

    }];
    
    //允许点击背景消失
    if (allowDismiss) {
        if (!self.stickerMaskView) {
            //可以让当前view消失，而且不影响后面的点击事件
            TouchableMaskView *maskView = [[TouchableMaskView alloc] initWithFrame:self.superview.bounds];
            maskView.backgroundColor = UIColor.clearColor;
            maskView.userInteractionEnabled = YES;
            @weakify(self)
            maskView.onTapOutside = ^{
                @strongify(self)
                [self hideStickerPicker];
            };
            _stickerMaskView = maskView;
        }
        [self.superview insertSubview:self.stickerMaskView belowSubview:self];
    }
    
}

- (void)showStickerPicker{
    
    [self showStickerPickerWithAllowTapDismiss:YES];
    
}

- (void)hideStickerPicker{
    
    if (self.stickerMaskView) {
        [self.stickerMaskView removeFromSuperview];
        self.stickerMaskView = nil;
    }
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(self.jk_height);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.superview layoutIfNeeded];
    }completion:^(BOOL finished) {
        self.hidden = YES;
    }];
    
}



#pragma mark - Setup

- (void)setupToolBar {
    self.backgroundColor = UIColor.mi_1_color;
    self.layer.cornerRadius = 14;
    self.layer.masksToBounds = YES;
    //这个阴影效果挺好，感觉可以全局用这个色
    [self jk_shadowWithColor:UIColor.mi_3_color offset:CGSizeMake(0, -2) opacity:0.5 radius:5];
    
    UIView *toolBarContainer = [[UIView alloc] init];
    [self addSubview:toolBarContainer];

    self.toolBar = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:({
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.itemSize = CGSizeMake(36, 36);
        layout.minimumLineSpacing = 20;
        if (self.showCloseButton) {
            layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 22);
        }else {
            layout.sectionInset = UIEdgeInsetsMake(0, 22, 0, 22);
        }
        layout;
    })];
    
    self.toolBar.delegate = self;
    self.toolBar.dataSource = self;
    self.toolBar.showsHorizontalScrollIndicator = NO;
    self.toolBar.backgroundColor = UIColor.clearColor;;
    [self.toolBar registerClass:[USStickerToolViewCell class] forCellWithReuseIdentifier:@"USStickerToolViewCell"];
    [toolBarContainer addSubview:self.toolBar];

    
    if (self.showCloseButton) {
        self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.closeButton setImage:[UIImage imageNamed:@"normal_close"] forState:0];
        [self.closeButton addTarget:self action:@selector(closeButtonTapped) forControlEvents:UIControlEventTouchUpInside];
        [toolBarContainer addSubview:self.closeButton];
        
        [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(toolBarContainer).offset(16);
            make.centerY.equalTo(toolBarContainer);
            make.width.height.mas_equalTo(28);
        }];
    }
    
    if (self.showEmptyButton) {
        self.emptyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.emptyButton setImage:[UIImage imageNamed:@"normal_empty"] forState:0];
        [self.emptyButton addTarget:self action:@selector(emptyButtonTapped) forControlEvents:UIControlEventTouchUpInside];
        [toolBarContainer addSubview:self.emptyButton];

        [self.emptyButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(toolBarContainer).offset(-16);
            make.centerY.equalTo(toolBarContainer);
            make.width.height.mas_equalTo(28);
        }];
    }

    [self.toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        if (self.showCloseButton) {
            make.left.mas_equalTo(self.closeButton.mas_right).offset(12);
        }else{
            make.left.mas_equalTo(toolBarContainer);
        }
        if (self.showEmptyButton) {
            make.right.mas_equalTo(self.emptyButton.mas_right).offset(-12);
        }else{
            make.right.mas_equalTo(toolBarContainer);
        }
        make.top.bottom.equalTo(toolBarContainer);
    }];
 

    [toolBarContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self);
        make.height.mas_equalTo(56);
    }];
}

- (void)setupPageView {
    self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    self.pageViewController.dataSource = self;
    self.pageViewController.delegate = self;

    self.pageViewController.view.backgroundColor = UIColor.clearColor;
    
    
    for (NSInteger i = 0; i < self.stickerGroups.count; i++) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

        USStickerModel *group = self.stickerGroups[i];
        if (group.size.width > 0) {
            layout.itemSize = group.size;
        }else{
            CGFloat width = (ScreenWidth - 16 * 2 - 10 * 3)/4.0;
            if (width > 100) {
                width = 100;
            }
            layout.itemSize = CGSizeMake(width , width);
        }
        
        layout.footerReferenceSize = CGSizeMake(self.jk_width, 44);

        
        layout.minimumInteritemSpacing = 10;
        layout.minimumLineSpacing = 10;
        layout.sectionInset = UIEdgeInsetsMake(12, 16, 0, 16);
        UICollectionViewController *vc = [[UICollectionViewController alloc] initWithCollectionViewLayout:layout];
        vc.view.backgroundColor = UIColor.clearColor;
        vc.collectionView.backgroundColor = UIColor.clearColor;
        vc.collectionView.delegate = self;
        vc.collectionView.dataSource = self;
        vc.collectionView.tag = i;
        [vc.collectionView registerNib:[UINib nibWithNibName:@"UIStickerFooterView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UIStickerFooterViewId"];
        [vc.collectionView registerClass:[USStickerViewCell class] forCellWithReuseIdentifier:@"USStickerViewCell"];
        [self.pageControllers addObject:vc];
    }

    if (self.pageControllers.count > 0) {
        [self.pageViewController setViewControllers:@[self.pageControllers[0]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    }

    [self addSubview:self.pageViewController.view];
    self.pageViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
    [self.pageViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.toolBar.mas_bottom);
        make.left.right.bottom.equalTo(self);
    }];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.strokeColor = UIColor.mi_3_color.CGColor;
    shapeLayer.lineWidth = 1.2;
    shapeLayer.lineCap = kCALineCapRound;
    shapeLayer.lineDashPattern = @[@8, @8];

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(16, 56)];
    [path addLineToPoint:CGPointMake(ScreenWidth - 32, 56 - 1.2)];
    
    shapeLayer.path = path.CGPath;
    [self.layer addSublayer:shapeLayer];
}

-(void)closeButtonTapped{
    [USFeedbackTool impactSoft];

    [self hideStickerPicker];
    
    if ([self.delegate respondsToSelector:@selector(stickerPickerViewClose)]) {
        [self.delegate stickerPickerViewClose];
    }
}
-(void)emptyButtonTapped{
    if ([self.delegate respondsToSelector:@selector(stickerPickerViewDidSelectEmpty)]) {
        [USFeedbackTool impactSoft];

        [self.delegate stickerPickerViewDidSelectEmpty];
    }
   
}
#pragma mark - ToolBar CollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return collectionView == self.toolBar ? self.stickerGroups.count : self.stickerGroups[collectionView.tag].stickers.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (collectionView == self.toolBar) {
        
        USStickerToolViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USStickerToolViewCell" forIndexPath:indexPath];
        
        USStickerModel *model = self.stickerGroups[indexPath.item];

        cell.imgView.image = [UIImage imageNamed:model.name];
        
         return cell;
    }else{
        
        USStickerViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USStickerViewCell" forIndexPath:indexPath];
         
    
        USStickerModel *model = self.stickerGroups[collectionView.tag].stickers[indexPath.item];
        
        cell.imgView.image = [UIImage imageNamed:model.name];
        
        return cell;
    }
    
 
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.toolBar) {
        [USFeedbackTool impactSoft];

        NSInteger newIndex = indexPath.item;
        UIPageViewControllerNavigationDirection direction = newIndex > self.currentGroupIndex ? UIPageViewControllerNavigationDirectionForward : UIPageViewControllerNavigationDirectionReverse;
        [self.pageViewController setViewControllers:@[self.pageControllers[newIndex]] direction:direction animated:YES completion:nil];
        self.currentGroupIndex = newIndex;
        [self.toolBar selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
    } else {
        [USFeedbackTool impactMedium];

        USStickerModel *sticker = self.stickerGroups[collectionView.tag].stickers[indexPath.item];
        if ([self.delegate respondsToSelector:@selector(stickerPickerView:didSelectSticker:)]) {
            [self.delegate stickerPickerView:self didSelectSticker:sticker];
        }
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
           UICollectionReusableView *footerView =
           [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                                              withReuseIdentifier:@"UIStickerFooterViewId"
                                                     forIndexPath:indexPath];
           return footerView;
       }

       return [UICollectionReusableView new];
    
}

#pragma mark - UIPageViewController Delegate/DataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    NSInteger index = [self.pageControllers indexOfObject:(UICollectionViewController *)viewController];
    return index > 0 ? self.pageControllers[index - 1] : nil;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    NSInteger index = [self.pageControllers indexOfObject:(UICollectionViewController *)viewController];
    return index < self.pageControllers.count - 1 ? self.pageControllers[index + 1] : nil;
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (completed) {
        UICollectionViewController *vc = (UICollectionViewController *)pageViewController.viewControllers.firstObject;
        self.currentGroupIndex = vc.collectionView.tag;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentGroupIndex inSection:0];
        [self.toolBar selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
    }
}

@end
